﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Facebook;

namespace Chilis.CRM.Services
{
    public class FacebookService
    {
        string FACEBOOK_APP_ID = "";
        string FACEBOOK_SECRET = "";
        string CHILIS_PROFILE_ID = "";
        string FACEBOOK_ACCESS_TOKEN = "";

        public FacebookService() {
            
            FACEBOOK_APP_ID = ConfigurationManager.AppSettings["FACEBOOK_APP_ID"];
            FACEBOOK_SECRET = ConfigurationManager.AppSettings["FACEBOOK_SECRET"];
            CHILIS_PROFILE_ID = ConfigurationManager.AppSettings["CHILIS_PROFILE_ID"];
            FACEBOOK_ACCESS_TOKEN = ConfigurationManager.AppSettings["FACEBOOK_ACCESS_TOKEN"];
        }

        public void AgregarConfiguracion(Configuration configuracion, string llave, string valor)
        {
            
            configuracion.AppSettings.Settings.Add(llave, valor);
            configuracion.Save();
            FACEBOOK_ACCESS_TOKEN = ConfigurationManager.AppSettings["FACEBOOK_ACCESS_TOKEN"];
        }

        public void ModificarConfiguracion(Configuration configuracion, string llave, string valor)
        {
            configuracion.AppSettings.Settings[llave].Value = valor;
            configuracion.Save();
            FACEBOOK_ACCESS_TOKEN = ConfigurationManager.AppSettings["FACEBOOK_ACCESS_TOKEN"];
        }


        public string PublicarEnMuro(string mensaje)
        {
            dynamic fbResponse = WriteMessageToFacebookWall(mensaje, CHILIS_PROFILE_ID, FACEBOOK_ACCESS_TOKEN);

                string objectId = fbResponse.id;
                string[] objectIdArray  = objectId.Split('_');
                string authorId = objectIdArray[0];
                string postId = objectIdArray[1];

                return postId;
        }

        public dynamic WriteMessageToFacebookWall(string message, string facebookId, string token)
        {
            dynamic postResponse;

            try
            {
                postResponse = PostToFacebookWall(token, message, facebookId);

                return postResponse;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private static dynamic PostToFacebookWall(string token, string message, string facebookId)
        {

            FacebookClient FbApp = new FacebookClient(token);
            IDictionary<string, object> postArgs = new Dictionary<string, object>();
            postArgs["message"] = message;
            if (token != null) postArgs["access_token"] = token;
            postArgs["uid"] = facebookId;
            var result = FbApp.Post("/" + facebookId + "/feed", postArgs);

            return result;
        }

    }
}
